﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Net.Mail;

namespace EuroAudit
{
    public partial class DocList : System.Web.UI.Page
    {
        GlobalF GFunc = new GlobalF();
        static string ActiveTab;
        Button cmdShow;//komanda dokumentu veidu atlasei
        Button cmdStat;//komanda statistikas parādīšanai

        //GlobalF.AppOptions AO = new GlobalF.AppOptions();

        //FtpWebRequest FWR = (FtpWebRequest)FtpWebRequest.Create("ftp://localhost");
        //FWR.Method = WebRequestMethods.Ftp

        protected void Page_Load(object sender, EventArgs e)
        {
            string OID = "";
            string DocT = "";
            string AuthString = " AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ")";
            GFunc.InitO();
            if (Session["UserName"] == null | Session["UserName"].ToString() == "" | Session["UserName"].ToString() == "guest")
            {
                Response.Redirect("Login.aspx", true);
                //return;
            }
            if (IsPostBack == false)
            {
                string a1 = Request.UserAgent;
                string a2 = Request.UserHostAddress;
                string a3 = Request.UserHostName;
                string a4 = Request.UserLanguages[0];
            }
            //if (Session["IsAdmin"].ToString() == "1")
            //{
                cmdNew.Visible = true;
                //cmdNewU.Visible = true;
            //}
            //else
            //{
            //    cmdNew.Visible = false;
                //cmdNewU.Visible = false;
            //}
            NameValueCollection HRStr = Request.QueryString;
            if (HRStr.GetValues("DocEdit") != null)
            {
                string[] DocID = HRStr.GetValues("DocEdit");
                EditDoc(DocID[0]);
            }
            if (HRStr.GetValues("NodePath") != null)
            {
                //HtmlTextWriter HTW=new HtmlTextWriter();
                string[] NodeP = HRStr.GetValues("NodePath");
                string[] NodePS = NodeP[0].Split('/');
                OID = NodePS[2];
                string QStr = "SELECT OrgID, OrgName FROM org WHERE RecStatus=0 AND OrgID='" + OID + "' " + AuthString;
                DataSet dsList = GFunc.GetData(QStr, "WebCNS", false);
                if (dsList.Tables.Count > 0)
                {
                    if (dsList.Tables[0].Rows.Count > 0)
                    {
                        lblOrgCap.Text = dsList.Tables[0].Rows[0]["OrgName"].ToString();
                        lblOrgID.Text = dsList.Tables[0].Rows[0]["OrgID"].ToString();
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
                LoadDoc(OID, DocT);
                SetActiveDocTab();
            }
            if (IsPostBack)
            {
                if (_RESULT.Text == "OKcmdDel")
                {
                    cmdDel_Click(sender, e);
                    _RESULT.Text = "";
                }
            }
            /*ddlDocType.DataSource = GFunc.GetData("SELECT Nos, Info FROM spr WHERE RecStatus=0 AND SprID='DocType' GROUP BY Nos ORDER BY Nos", "WebCNS", false);
            ddlDocType.DataValueField = "Nos";
            ddlDocType.DataTextField = "Info";
            ddlDocType.DataBind();
            */
        }
        void SetActiveDocTab()
        {

            foreach (TableRow tr in tCmd.Rows)
            {
                foreach (TableCell tc in tr.Cells)
                {
                    foreach (Control c in tc.Controls)
                    {
                        if (c is Button)
                        {
                            Button b = c as Button;
                            if (ActiveTab == c.ID)
                            {
                                b.CssClass = "cmdTabsActive";
                            }
                            else
                            {
                                b.CssClass = "cmdTabs";
                            }
                        }
                    }
                }
            }
        }

        void LoadDoc(string OrgID, string DocType)
        {
            DataSet dsList;
            //DataSet dsGroupList;
            TableHeaderCell thcNewCell;
            TableHeaderRow thrNewRow;
            TableCell tcNewCell;
            TableRow trNewRow;
            Button cmdEdit;//komanda dokumenta labošanai
            Button cmdShowDoc;//komanda dokumenta ielādei
            string WhereDocT = "";
            string WhereAllDocT = "";
            string AuthString = " AND (AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ")";

            /*string LastStruct = "";
            string CurrStruct = "";
            string LastNod = "";
            string CurrNod = "";
            */
            //Button cmdGEdit;
            //string UsersInGroup;
            //izveidojam pārslēdzējus
            tCmd.Rows.Clear();
            //pievienojam statistikas pārslēdzēju
            trNewRow = new TableRow();
            tcNewCell = new TableCell();
            cmdStat = new Button();
            cmdStat.ID = "cmdStat" + OrgID;
            cmdStat.Text = "Statistika";
            cmdStat.CssClass = "cmdTabs";
            if (ActiveTab == cmdStat.ID)
            {
                cmdStat.CssClass = "cmdTabsActive";
            }
            else
            {
                cmdStat.CssClass = "cmdTabs";
            }
            cmdStat.Width = Unit.Percentage(90);
            cmdStat.Font.Size = FontUnit.Point(8);
            cmdStat.Click += new EventHandler(cmdStat_Click);
            tcNewCell.Controls.Add(cmdStat);
            trNewRow.Cells.Add(tcNewCell);
            tCmd.Rows.Add(trNewRow);
            
            //pievienojam dokumentu tipu pārslēdzējus
            string QStrCmd = "SELECT Nos, Info FROM spr WHERE RecStatus=0 AND SprID='DocType' " + AuthString + " ORDER BY Nos";
            dsList = GFunc.GetData(QStrCmd, "WebCNS", false);
            if (dsList.Tables.Count > 0)
            {
                if (dsList.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow rowC in dsList.Tables[0].Rows)
                    {
                        trNewRow = new TableRow();
                        tcNewCell = new TableCell();
                        cmdShow = new Button();
                        cmdShow.ID = "cmdShow_" + rowC["Nos"].ToString() + "_" + OrgID;
                        cmdShow.Text = rowC["Nos"].ToString();
                        cmdShow.CssClass = "cmdTabs";
                        if (ActiveTab == cmdShow.ID)
                        {
                            cmdShow.CssClass = "cmdTabsActive";
                        }
                        else
                        {
                            cmdShow.CssClass = "cmdTabs";
                        }
                        cmdShow.Width = Unit.Percentage(90);
                        //-css-cmdShow.Font.Size = FontUnit.Point(8);
                        cmdShow.Click += new EventHandler(cmdShow_Click);
                        tcNewCell.Controls.Add(cmdShow);
                        trNewRow.Cells.Add(tcNewCell);

                        tCmd.Rows.Add(trNewRow);
                        //izveidojam nosacījumu, ja lietotājam ir jāparāda visi pieejamie dokumenti
                        if (WhereAllDocT == string.Empty)
                        {
                            WhereAllDocT = " AND (DocType = '" + rowC["Nos"].ToString() + "' ";
                        }
                        else
                        {
                            WhereAllDocT = WhereAllDocT + " OR DocType = '" + rowC["Nos"].ToString() + "' ";
                        }
                    }
                    WhereAllDocT = WhereAllDocT + ")";
                }
            }

            if (DocType != string.Empty)
            {
                WhereDocT = " AND DocType='" + DocType + "' ";
            }
            else
            {
                WhereDocT = WhereAllDocT;
            }
            tDocs.Rows.Clear();
            //pievienojam dokumentu sarakstu
            string QStr = "SELECT DocID, DocNum, DocDate, DocName, DocDescr, OrgID, DocType, Link FROM doc WHERE RecStatus=0 AND OrgID='" + OrgID + "' " + WhereDocT + " ORDER BY DocType, DocDate";
            dsList = GFunc.GetData(QStr, "WebCNS", false);
            if (dsList.Tables.Count > 0)
            {
                if (dsList.Tables[0].Rows.Count > 0)
                {
                    thrNewRow = new TableHeaderRow();
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "Labot";
                    thrNewRow.Cells.Add(thcNewCell);
                    thcNewCell = new TableHeaderCell();
                    thcNewCell.Text = "Ielādēt";
                    thrNewRow.Cells.Add(thcNewCell);
                    foreach (DataColumn Col in dsList.Tables[0].Columns)
                    {
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = Col.ColumnName;
                        thrNewRow.Cells.Add(thcNewCell);
                    }
                    tDocs.Rows.AddAt(0, thrNewRow);

                    //CurrStruct = row["Strukturvieniba"].ToString();
                    //CurrNod = row["Nodala"].ToString();
                    
                    foreach (DataRow row in dsList.Tables[0].Rows)
                    {
                        trNewRow = new TableRow();
                        //pievienojam rediģēšanas komandu
                        tcNewCell = new TableCell();
                        //if (Session["IsAdmin"].ToString() == "1")
                        {
                            cmdEdit = new Button();
                            cmdEdit.ID = "DocEdit" + row["DocID"].ToString();
                            cmdEdit.Text = "Labot";
                            cmdEdit.CssClass = "cmdEdit";
                            cmdEdit.CommandArgument = row["DocID"].ToString();
                            cmdEdit.PostBackUrl = "#pEdit";
                            cmdEdit.Click += new EventHandler(cmdEdit_Click);
                            tcNewCell.Controls.Add(cmdEdit);
                            Label BkmListG = new Label();
                            BkmListG.Text = "<a name=\"" + row["DocID"].ToString() + "\"></a>";
                            //BkmListG.Visible = false;
                            tcNewCell.Controls.Add(BkmListG);
                        }
                        trNewRow.Cells.Add(tcNewCell);
                        //pievienojam dok. ielādes komandu
                        tcNewCell = new TableCell();
                        //if (Session["IsAdmin"].ToString() == "1")
                        //{
                            cmdShowDoc = new Button();
                            cmdShowDoc.ID = "ShowDoc" + row["DocID"].ToString();
                            cmdShowDoc.Text = "Ielādēt";
                            cmdShowDoc.CssClass = "cmdEdit";
                            //cmdShowDoc.PostBackUrl = GlobalF.AppOptions["DocPath"] + row["Link"].ToString();
                            cmdShowDoc.Click += new EventHandler(cmdShowDoc_Click);
                            tcNewCell.Controls.Add(cmdShowDoc);
                        //}
                        trNewRow.Cells.Add(tcNewCell);

                        foreach (DataColumn Col in dsList.Tables[0].Columns)
                        {
                            tcNewCell = new TableCell();
                            string a = Col.DataType.Name;
                            if (Col.DataType.Name == "DateTime")
                            {
                                DateTime DT = (DateTime)row[Col];
                                tcNewCell.Text = DT.ToString("dd.MM.yyyy");
                            }
                            else
                            {
                                tcNewCell.Text = row[Col].ToString() + "&nbsp";
                            }
                            trNewRow.Cells.Add(tcNewCell);
                        }
                        tDocs.Rows.Add(trNewRow);

                    }
                }
            }
        }


        void cmdStat_Click(object sender, EventArgs e)
        {
            string OrgID;
            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            ActiveTab = b.ID;
            //cmdStat.CssClass = "cmdTabsActive";
            SetActiveDocTab();
            OrgID = b.ID.Substring(7);
            tDocs.Rows.Clear();
            TableRow trNewRow = new TableRow();
            TableCell tcNewCell = new TableCell();
            tcNewCell.Text = "Organizācijas " + OrgID + " statisktika";
            trNewRow.Cells.Add(tcNewCell);
            tDocs.Rows.Add(trNewRow);
            //throw new NotImplementedException();
        }

        void cmdShow_Click(object sender, EventArgs e)
        {
            string DocT;
            string OrgID;
            string[] SplitS;

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            ActiveTab = b.ID;
            //b.CssClass = "cmdTabsActive";
            SetActiveDocTab();
            SplitS = b.ID.Substring(8).Split('_');
            DocT = SplitS[0];
            OrgID = SplitS[1];
            LoadDoc(OrgID, DocT);

            //throw new NotImplementedException();
        }

        void cmdShowDoc_Click(object sender, EventArgs e)
        {
            string DocID;
            string QString;
            DataSet ds;

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            DocID = b.ID.Substring(7);
            QString = "SELECT * FROM doc WHERE RecStatus=0 AND DocID='" + DocID + "'";
            ds = GFunc.GetData(QString, "WebCNS", false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    Response.Redirect(GlobalF.AppOptions["DocPath"] + row["Link"].ToString(), true);
                }
            }
            //throw new NotImplementedException();
        }

        void EditDoc(string DocID)
        {
            string WhereAccOrg = " AND (org.AccessU LIKE '%;guest;%' " + Session["WhereGroups"].ToString().Replace("AccessU", "org.AccessU").Replace("AccessG", "org.AccessG") + ")";//pieejas tiesības organizācijām
            string WhereAccDocType = " AND (spr.AccessU LIKE '%;guest;%' " + Session["WhereGroups"].ToString().Replace("AccessU", "spr.AccessU").Replace("AccessG", "spr.AccessG") + ")";//pieejas tiesības dokumentu tipiem
            string QString;
            DataSet ds;
            DateTime StrDate;

            lbDocType.ClearSelection();
            lbDocType.DataSource = GFunc.GetData("SELECT Nos, Info FROM spr WHERE RecStatus=0 AND SprID='DocType' GROUP BY Nos ORDER BY Nos", "WebCNS", false);
            lbDocType.DataValueField = "Nos";
            lbDocType.DataTextField = "Info";
            lbDocType.DataBind();

            //QString = "SELECT * FROM doc WHERE RecStatus=0 AND DocID='" + DocID + "'";
            QString = "SELECT doc.* " +
                "FROM (doc LEFT JOIN org ON doc.OrgID = org.OrgID) LEFT JOIN spr ON doc.DocType = spr.Nos " +
                "WHERE doc.RecStatus=0 AND spr.SprID='DocType' AND doc.DocID='" + DocID + "'" + WhereAccOrg + WhereAccDocType + " ";

            ds = GFunc.GetData(QString, "WebCNS", false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    txtDocID.Text = row["DocID"].ToString();
                    txtDocType.Text = row["DocType"].ToString();
                    txtDocNum.Text = row["DocNum"].ToString();
                    //StrDate = DateTime.ParseExact(row["DocDate"].ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                    StrDate = (DateTime)row["DocDate"];
                    txtDocDate.Text = StrDate.ToString("dd.MM.yyyy");
                    txtDocName.Text = row["DocName"].ToString();
                    txtDocDescr.Text = row["DocDescr"].ToString();
                    txtOrgID.Text = row["OrgID"].ToString();
                    txtLink.Text = row["Link"].ToString();
                    lblDocPath.Text = GlobalF.AppOptions["DocPath"] + txtLink.Text;
                }
                else
                {
                    lblErr.Text = "Dokuments nav pieejams.";
                }
            }
            else
            {
                lblErr.Text = "Dokuments nav pieejams.";
            }
            chMail.Checked = false;
            txtDocType.Enabled = false;//false
            txtLink.ReadOnly = true;
            cmdLink.Enabled = false;//false//
            
            pEdit.Visible = true;
            upFile.Update();
            pFile.Visible = true;

        }

        void cmdEdit_Click(object sender, EventArgs e)
        {
            string Rec2Edit;
            
            /*gvAccessG.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvAccessG.DataBind();
            //gvAccessG.AutoGenerateSelectButton = true;
            gvAccessG.Visible = false;
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessU.DataSource = GFunc.GetData("SELECT User, LongName, Groups FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvAccessU.DataBind();
            //gvAccessU.AutoGenerateSelectButton = true;
            gvAccessU.Visible = false;
            gvEditU.DataSource = GFunc.GetData("SELECT User, LongName, Groups FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvEditU.DataBind();
            //gvEditU.AutoGenerateSelectButton = true;
            gvEditU.Visible = false;
             */

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            Rec2Edit = b.ID.Substring(7);
            EditDoc(Rec2Edit);
            cmdClose.PostBackUrl = "#" + b.CommandArgument;
            //throw new NotImplementedException();
        }

        protected void cmdNew_Click(object sender, EventArgs e)
        {
            lbDocType.ClearSelection();
            lbDocType.DataSource = GFunc.GetData("SELECT Nos, Info FROM spr WHERE RecStatus=0 AND SprID='DocType' GROUP BY Nos ORDER BY Nos", "WebCNS", false);
            lbDocType.DataValueField = "Nos";
            lbDocType.DataTextField = "Info";
            lbDocType.DataBind();


            txtDocID.Text = "";
            txtDocType.Text = "";
            txtDocNum.Text = "";
            txtDocDate.Text = DateTime.Now.ToString("dd.MM.yyyy");
            txtDocName.Text = "";
            txtDocDescr.Text = "";
            txtOrgID.Text = lblOrgID.Text;
            txtLink.Text = "";
            lblDocPath.Text = "";
            chMail.Checked = false;
            txtDocType.Enabled = true;
            txtLink.ReadOnly = true;
            cmdLink.Enabled = true;
            pEdit.Visible = true;
            upFile.Update();
            pFile.Visible = true;

        }

        protected void cmdClose_Click(object sender, EventArgs e)
        {
            lblErr.Text = "";
            pEdit.Visible = false;
            upFile.Update();
            pFile.Visible = false;
            
        }

        protected void cmdDel_Click(object sender, EventArgs e)
        {
            string StrDel;

            lblErr.Text = "";
            StrDel = "UPDATE doc SET RecStatus=1 WHERE DocID='" + txtDocID.Text + "'";
            GFunc.GetData(StrDel, "WebCNS", false);
            //TODO: izveidot procedūru faila dzēšanai vai pārsaukšanai uz servera
            lblErr.Text = "Dokuments izdzēsts.";
        }

        public string[] GetFileList(string CheckFolder)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            WebResponse response = null;
            StreamReader reader = null;
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(CheckFolder));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(GlobalF.AppOptions["FTP user"], GlobalF.AppOptions["FTP password"]);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                reqFTP.UsePassive = false;
                response = reqFTP.GetResponse();
                reader = new StreamReader(response.GetResponseStream(),Encoding.GetEncoding(1257));
                Encoding SEnc = reader.CurrentEncoding;
                
                string line = reader.ReadLine();
                
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                // to remove the trailing '\n'
                if (result.Length > 0)
                {
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                }
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                return null;
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            string[] c = new string[11];
            string QString = "";
            string LastID = "";
            DataSet dsLastID;
            DateTime StrDate;
            string NewFileName = "";
            bool IsNewRec = string.IsNullOrEmpty(txtDocID.Text);

            lblErr.Text = "";
            /* Dokumenta nosaukums tiks ģenerēts automātiski no aizpildītajiem laukiem.
            if (string.IsNullOrEmpty(txtDocName.Text) == true)
            {
                lblErr.Text = "Nav norādīts dokumenta nosaukums!";
                return;
            }*/
            if (string.IsNullOrEmpty(txtDocNum.Text) == true)
            {
                lblErr.Text = "Nav norādīts dokumenta numurs!";
                return;
            }
            if (string.IsNullOrEmpty(txtDocType.Text) == true)
            {
                lblErr.Text = "Nav norādīts dokumenta tips!";
                return;
            }
            if (string.IsNullOrEmpty(txtOrgID.Text) == true)
            {
                lblErr.Text = "Nav norādīts organizācijas kods!";
                return;
            }
            if (fuFile.PostedFile.FileName == string.Empty)
            {
                lblErr.Text = "Nav norādīts lejuplādējamais dokuments!";
                return;
            }
            if (txtDocDate.Text == string.Empty)
            {
                lblErr.Text = "Nav norādīts datums!";
                return;
            }
            string[] CheckDocName = txtDocName.Text.Split('_');
            if (CheckDocName.Length != 5)
            {
                string[] FileName = fuFile.PostedFile.FileName.Split('.');
                string FileExt = "";
                if (FileName.Length > 1)
                {
                    FileExt = "." + FileName[FileName.GetUpperBound(0)];
                }
                NewFileName += Convert.ToDateTime(txtDocDate.Text).ToString("yyyyMMdd");
                NewFileName += "_" + txtDocNum.Text;
                NewFileName += "_" + txtOrgID.Text;
                NewFileName += "_" + txtDocType.Text;
                NewFileName += "_" + DateTime.Now.ToString("MMddhhmmss");
                NewFileName += FileExt;
                txtDocName.Text = NewFileName;
            }
            
            if (txtLink.Text == string.Empty)
            {
                Guid Link = Guid.NewGuid();
                txtLink.Text = Link.ToString("N");
                lblDocPath.Text = GlobalF.AppOptions["DocPath"] + txtLink.Text;
            }
            try
            {

                if (fuFile.PostedFile.FileName != string.Empty)
                {
                    
                    
                    string OrgDir = "" + lblOrgCap.Text + "/" + txtDocType.Text + "/";
                    FtpWebRequest FTPReq;//pieprasījums direktoriju pārbaudei
                    FtpWebResponse FTPRes;//atbilde direktoriju pārbaudei
                    string CheckFolder = GlobalF.AppOptions["FTP server"];
                    //pieprasām failu sarakstu no FTP pamatdirektorijas
                    //un pārbaudam vai ir organizācijas direktorija
                    string[] FList = GetFileList(CheckFolder);
                    if (FList.Contains(lblOrgCap.Text) == false)
                    {
                        FTPReq = (FtpWebRequest)FtpWebRequest.Create(CheckFolder + lblOrgCap.Text + "/");
                        FTPReq.Credentials = new NetworkCredential(GlobalF.AppOptions["FTP user"], GlobalF.AppOptions["FTP password"]);

                        FTPReq.Method = WebRequestMethods.Ftp.MakeDirectory;
                        FTPRes = (FtpWebResponse)FTPReq.GetResponse();
                    }
                    CheckFolder = CheckFolder + lblOrgCap.Text + "/";
                    //pieprasām failu sarakstu no FTP organizācijas direktorijas
                    //un pārbaudam vai ir dok.tipa direktorija
                    FList = GetFileList(CheckFolder);
                    if (FList.Contains(txtDocType.Text) == false)
                    {
                        FTPReq = (FtpWebRequest)FtpWebRequest.Create(CheckFolder + txtDocType.Text + "/");
                        FTPReq.Credentials = new NetworkCredential(GlobalF.AppOptions["FTP user"], GlobalF.AppOptions["FTP password"]);

                        FTPReq.Method = WebRequestMethods.Ftp.MakeDirectory;
                        FTPRes = (FtpWebResponse)FTPReq.GetResponse();
                    }
                    //ielādējam failu
                    FtpWebRequest FWR = (FtpWebRequest)FtpWebRequest.Create(GlobalF.AppOptions["FTP server"] + OrgDir + txtDocName.Text); //fuFile.FileName
                    FWR.Credentials = new NetworkCredential(GlobalF.AppOptions["FTP user"], GlobalF.AppOptions["FTP password"]);
                    FWR.Method = WebRequestMethods.Ftp.UploadFile;
                    FWR.ContentLength = fuFile.FileBytes.Length;
                    Stream requestStream = FWR.GetRequestStream();
                    requestStream.Write(fuFile.FileBytes, 0, fuFile.FileBytes.Length);
                    requestStream.Close();


                }
                c[0] = "DocID='" + GFunc.EscapeSQLCahrs(txtDocID.Text) + "'";
                c[1] = "DocType='" + GFunc.EscapeSQLCahrs(txtDocType.Text) + "'";
                c[2] = "DocNum='" + GFunc.EscapeSQLCahrs(txtDocNum.Text) + "'";
                StrDate = DateTime.ParseExact(txtDocDate.Text, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                c[3] = "DocDate='" + StrDate.ToString("yyyy-MM-dd") + "'";
                c[4] = "DocName='" + GFunc.EscapeSQLCahrs(txtDocName.Text) + "'";
                c[5] = "DocDescr='" + GFunc.EscapeSQLCahrs(txtDocDescr.Text) + "'";
                c[6] = "OrgID='" + GFunc.EscapeSQLCahrs(txtOrgID.Text) + "'";
                c[7] = "Link='" + GFunc.EscapeSQLCahrs(txtLink.Text) + "'";
                c[8] = "UserEdit='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[9] = "UserAdd='" + GFunc.EscapeSQLCahrs(Session["UserName"].ToString()) + "'";
                c[10] = "TimeAdd='" + GFunc.EscapeSQLCahrs(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "'";
                if (string.IsNullOrEmpty(txtDocID.Text) == false)
                {
                    QString = "UPDATE doc SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + " WHERE " + c[0];
                }
                else
                {
                    QString = "INSERT INTO doc SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10];
                }
                dsLastID = GFunc.GetData(QString, "WebCNS", true);
                if (txtDocID.Text.Length == 0)
                {
                    if (dsLastID.Tables.Count > 0)
                    {
                        if (dsLastID.Tables["tLID"].Rows.Count > 0)
                        {
                            txtDocID.Text = dsLastID.Tables["tLID"].Rows[0]["LID"].ToString();
                        }
                    }
                }
                if (chMail.Checked == true)
                {
                    string MsgTo = "";
                    DataSet dsOMail = GFunc.GetData("SELECT Email FROM org WHERE RecStatus=0 AND OrgID='" + txtOrgID.Text + "'", "WebCNS", false);
                    if (dsOMail.Tables.Count > 0)
                    {
                        if (dsOMail.Tables[0].Rows.Count > 0)
                        {
                            if (string.IsNullOrEmpty(dsOMail.Tables[0].Rows[0]["Email"].ToString()))
                            {
                                lblErr.Text = "Dokuments tika saglabāts bez paziņojuma nosūtīšanas, jo klientam nav norādīts e-pasts.";
                                return;
                            }
                            else
                            {
                                MsgTo = dsOMail.Tables[0].Rows[0]["Email"].ToString();
                            }
                        }
                        else
                        {
                            lblErr.Text = "Dokuments tika saglabāts bez paziņojuma nosūtīšanas, jo klientam nav norādīts e-pasts.";
                            return;
                        }
                    }
                    else
                    {
                        lblErr.Text = "Dokuments tika saglabāts bez paziņojuma nosūtīšanas, jo klientam nav norādīts e-pasts.";
                        return;
                    }
                    MailMessage MMsg = new MailMessage();
                    MailAddress FromAdr=new MailAddress(Session["UserEmail"].ToString());
                    MMsg.From = FromAdr;
                    string[] MsgRcp = MsgTo.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < MsgRcp.GetLength(0); i++)
                    {
                        MMsg.To.Add(MsgRcp[i]);
                    }
                    //aizpildam CC lauku, ja DB ir norādīti e-pasti
                    string[] CCMail;
                    string CCOption = "";
                    DataSet dsOMailFrom = GFunc.GetData("SELECT OptValue FROM options WHERE OptType='GLOBAL' AND OptGroup='Mail' AND OptName='CC Users'", "WebCNS", false);
                    if (dsOMailFrom.Tables.Count > 0)
                    {
                        if (dsOMailFrom.Tables[0].Rows.Count > 0)
                        {
                            CCOption = dsOMailFrom.Tables[0].Rows[0]["OptValue"].ToString().Trim();
                        }
                    }
                    if (CCOption.Length > 0)
                    {
                        CCMail = CCOption.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; i < CCMail.Length; i++)
                        {
                            MailAddress CCAdr = new MailAddress(CCMail[i]);
                            MMsg.CC.Add(CCAdr);
                        }
                    }
                    MMsg.Subject = GlobalF.AppOptions["DocMailSubject"];
                    // HTML Body (remove HTML tags for plain text).
                    string NewDocMsg = "EUROAUDIT sistēmā tika publicēts jauns dokuments:";
                    if (IsNewRec == false)
                    {
                        NewDocMsg = "EUROAUDIT sistēmā tika labots sekojošs dokuments:";
                    }
                    string MsgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" +
                            "<HTML>" +
                            "<HEAD>" +
                            "	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=windows-1257\">" +
                            "</HEAD>" +
                            "<BODY LANG=\"lv-LV\" DIR=\"LTR\">" +
                            "<P><B>" + NewDocMsg + "</B></P>" +
                            "<P><BR>" +
                            "</P>" +
                            "<P>Dokumenta tips: <B>" + txtDocType.Text + "</B></P>" +
                            "<P>Dokumenta datums: <B>" + txtDocDate.Text + "</B> " +
                            "</P>" +
                            "<P>Dokumenta numurs: <B>" + txtDocNum.Text + "</B> " +
                            "</P>" +
                            "<P>Dokumenta nosaukums: <B>" + txtDocName.Text + "</B> " +
                            "</P>" +
                            "<P>Piezīmes: <B>" + txtDocDescr.Text + "</B> " +
                            "</P>" +
                            "<P>Saite piekļuvei bez autorizācijas: <A HREF=\"" + lblDocPath.Text + "\"><B>" + lblDocPath.Text + "</B> " +
                            "</P>" +
                            "</BODY>" +
                            "</HTML>";

                    MMsg.Body = MsgBody;
                    MMsg.IsBodyHtml = true;
                    
                    /*// ADD AN ATTACHMENT.
                    String sFile = @"C:\temp\Hello.txt";
                    MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);

                    oMsg.Attachments.Add(oAttch);
                    */
                    // : Replace with the name of your remote SMTP server.
                    SmtpClient SMTPmail = new SmtpClient();
                    SMTPmail.Host = GlobalF.AppOptions["SMTPServer"];
                    SMTPmail.Send(MMsg);

                    
                    MMsg.Dispose();
                    
                    //oAttch = null;

                }
                lblErr.Text = "Dokuments saglabāts.";
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }

        protected void cmdDocDate_Click(object sender, EventArgs e)
        {
            cDocDate.Visible = !cDocDate.Visible;
        }

        protected void cDocDate_SelectionChanged(object sender, EventArgs e)
        {
            txtDocDate.Text = cDocDate.SelectedDate.ToString("dd.MM.yyyy");
            cDocDate.Visible = false;
        }

        protected void cmdLink_Click(object sender, EventArgs e)
        {
            Guid Link = Guid.NewGuid();
            txtLink.Text = Link.ToString("N");
            lblDocPath.Text = GlobalF.AppOptions["DocPath"] + txtLink.Text;

        }

        protected void txtDocName_TextChanged(object sender, EventArgs e)
        {
            //txtDocDate.Text = "1";
        }

        protected void lbDocType_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtDocType.Text = lbDocType.SelectedItem.Value;
            
        }

        protected void txtOrgID_TextChanged(object sender, EventArgs e)
        {

        }

        protected void txtDocName_TextChanged1(object sender, EventArgs e)
        {

        }

        protected void chMail_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void cmdDelLn_Click(object sender, EventArgs e)
        {
            //
            string test = "";
        }


    }
}
